package pers.cyril.jdb.server.netty.handler;

import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import pers.cyril.jdb.common.channel.Session;
import pers.cyril.jdb.common.util.SessionUtils;
import pers.cyril.jdb.protocol.packet.LoginRequestPacket;
import pers.cyril.jdb.protocol.packet.LoginResponsePacket;

/**
 * LoginRequest 处理器
 *
 * @author Wang Cyril
 * @date 2024/5/16 21:21
 */
@ChannelHandler.Sharable
public class LoginRequestHandler extends SimpleChannelInboundHandler<LoginRequestPacket> {

    public static final LoginRequestHandler INSTANCE = new LoginRequestHandler();

    private LoginRequestHandler() {
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, LoginRequestPacket msg) throws Exception {

        //检查用户名密码是否正确
        LoginResponsePacket loginResponsePacket = new LoginResponsePacket();
        String userId;
        if ((userId = getUserId(msg)) == null) {
            loginResponsePacket.setUsername(msg.getUsername());
            loginResponsePacket.setSuccess(false);
            loginResponsePacket.setMessage("【" + msg.getUsername() + "】用户名密码不匹配，请重试");
            ctx.channel().writeAndFlush(loginResponsePacket);
            return;
        }

        loginResponsePacket.setUserId(userId);
        loginResponsePacket.setUsername(msg.getUsername());
        loginResponsePacket.setSuccess(true);
        loginResponsePacket.setMessage("登录成功");
        Session session = new Session();
        session.setUsername(msg.getUsername());
        session.setUserId(userId);
        SessionUtils.attachSession(ctx.channel(), session);
        ctx.channel().writeAndFlush(loginResponsePacket);

    }

    //TODO
    private String getUserId(LoginRequestPacket msg) {
        if ("admin".equals(msg.getUsername()) && "password".equals(msg.getPassword())) {
            return "1234";
        }
        return null;
    }
}
